﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.CodeDom.Compiler;
using System.CodeDom;
using System.Diagnostics;
using System.Reflection;
using System.Runtime;
using System.IO;
using System.Windows.Forms;

namespace CXMLStudioIDE.Common
{
    public class Compiler
    {
        #region Methods

        public CompilerResults CompileClass(string[] sz_BusinessEntityCode, string AssemblyName)
        {
            CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
            System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
            //Make sure we generate an EXE, not a DLL
            parameters.GenerateInMemory = true;
            parameters.TreatWarningsAsErrors = false;
            parameters.GenerateExecutable = false;
            parameters.CompilerOptions = "/optimize";
            parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("System.Xml.dll");
            parameters.OutputAssembly = AssemblyName + ".dll";
            CleanAssembly(AssemblyName + ".dll");
            CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, sz_BusinessEntityCode);
            return results;
        }

        protected void CleanAssembly(string sZ_AssemblyFullName)
        {
                string location = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), sZ_AssemblyFullName);
                if (File.Exists(location))
                {
                    //System.GC.Collect();
                    //System.GC.WaitForPendingFinalizers(); 
                    //Process[] prcList = Process.GetProcesses();
                    //System.Reflection.AssemblyName[] ExesAndDlls = System.Reflection.Assembly.GetExecutingAssembly().GetReferencedAssemblies();
                    //foreach (Process p in prcList)
                    //{
                    //    if (p.ProcessName == "notepad")
                    //    {
                    //        p.Kill();
                    //    }
                    //}
                    try
                    {
                        File.Delete(location);
                    }
                    catch (UnauthorizedAccessException uaex)
                    {
                        /** For some reason when closing DataDictionary 
                         * and opening it again it cannot delete the assembly
                         * returns an Access denied error.
                         * */
                    }
                }
        }

        #endregion
    }
}
